package com.fs.common.interceptor;

import com.fs.sys.entityservice.AppEntityService;
import com.fs.common.bean.UserContext;
import com.fs.common.bean.UserContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 客户端模式拦截器
 *
 * @author  LiuQi 2024/9/25-19:21
 * @version V1.0
 **/
@Component
@Slf4j
public class ClientInterceptor implements HandlerInterceptor {
    @Autowired
    private AppEntityService appService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查是否是客户端模式
        UserContext userContext = UserContextHolder.get().orElse(null);
        if (null == userContext) {
            // 未登录，可能是其它接口，继续处理
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        if (!userContext.getIsClient()) {
            // 非客户端模式
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        // 应用模式，只允许调用查询接口，或者站内信相关接口
        String uri = request.getRequestURI();
        if (uri.endsWith("page-query") || uri.endsWith("query") || uri.contains("/detail/") || uri.contains("/base/inbox-msg")) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        log.error("客户端无权限调用指定接口，地址：{}", uri);
        response.setStatus(401);
        return false;
    }
}
